package cn.xiaoming.car.server.account.service.impl;

import cn.xiaoming.car.server.account.dao.persist.repository.IUserRepository;
import cn.xiaoming.car.server.account.pojo.entity.User;
import cn.xiaoming.car.server.account.pojo.param.UserAddNewParam;
import cn.xiaoming.car.server.account.pojo.param.UserLoginInfoParam;
import cn.xiaoming.car.server.account.pojo.param.UserUpdataPasswordParam;
import cn.xiaoming.car.server.account.pojo.vo.UserListItemVO;
import cn.xiaoming.car.server.account.pojo.vo.UserLoginInfoVO;
import cn.xiaoming.car.server.account.pojo.vo.UserLoginResultVO;
import cn.xiaoming.car.server.account.pojo.vo.UserStandardVO;
import cn.xiaoming.car.server.account.service.IUserService;
import cn.xiaoming.car.server.common.ex.ServiceException;
import cn.xiaoming.car.server.common.pojo.vo.PageData;
import cn.xiaoming.car.server.common.util.JWTUtil;
import cn.xiaoming.car.server.common.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理用户数据的业务实现类
 *
 * @author java@john.cn
 * @version 1.0
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Value("${xiaoming-car.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private IUserRepository userRepository;

    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(10);

    public UserServiceImpl() {
        log.debug("创建业务类对象：UserServiceImpl");
    }

    @Override
    public UserLoginResultVO login(UserLoginInfoParam userLoginInfoParam) {
        log.debug("开始处理【用户登录】的业务，参数：{}", userLoginInfoParam);
        String username = userLoginInfoParam.getUsername();

        UserLoginInfoVO userLoginInfoVO = userRepository.getLoginInfoByUsername(username);
        //判断用户是否存在
        String rawPassword = userLoginInfoParam.getPassword();
        String encodedPassword = userLoginInfoVO.getPassword();
        if (passwordEncoder.matches(rawPassword, encodedPassword)) {
            //生成JWT Map
            Map<String, Object> claims = new HashMap<>();
            // claims.put("i", 1);
            claims.put("id", userLoginInfoVO.getId());
            claims.put("username", userLoginInfoVO.getUsername());
            //生成JWT
            String token = JWTUtil.getToken(claims);
            UserLoginResultVO userLoginResultVO = new UserLoginResultVO();
            BeanUtils.copyProperties(userLoginInfoVO, userLoginResultVO);
            userLoginResultVO.setToken(token);
            return userLoginResultVO;
        } else {
            String message = "登陆失败！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
    }

    @Override
    public void addNew(UserAddNewParam userAddNewParam) {
        // 检查用户名是否被占用
        {
            String username = userAddNewParam.getUsername();
            int count = userRepository.countByUsername(username);
            if (count > 0) {
                String message = "注册用户失败，用户名已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }
        // 检查手机号是否被占用
        {
            String phone = userAddNewParam.getPhone();
            int count = userRepository.countByPhone(phone);
            if (count > 0) {
                String message = "注册用户失败，手机号码已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        // 检查邮箱是否被占用
        {
            String email = userAddNewParam.getEmail();
            int count = userRepository.countByEmail(email);
            if (count > 0) {
                String message = "注册用户失败，电子邮箱已经被占用！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }
        User user = new User();
        BeanUtils.copyProperties(userAddNewParam, user);
        String encodedPassword = passwordEncoder.encode(userAddNewParam.getPassword());
        user.setPassword(encodedPassword);

        int rows = userRepository.insert(user);
        if (rows != 1) {
            String message = "添加用户失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除用户】的业务，参数：{}", id);
        Object queryResult = userRepository.getStandardById(id);
        if (queryResult == null) {
            String message = "删除用户失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        log.debug("即将执行删除数据，参数：{}", id);
        int rows = userRepository.deleteById(id);
        if (rows != 1) {
            String message = "删除用户失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
    }

    @Override
    public void updataPassword(Long id,UserUpdataPasswordParam userUpdataPasswordParam) {
        //TODO 判断用户ID是否存在
        //TODO 检查旧密码是否正确
        UserStandardVO currentUser = userRepository.getStandardById(id);

        String newPassword=userUpdataPasswordParam.getNewPassword();
        User user = new User();
        user.setId(id);
        String encodedPassword = passwordEncoder.encode(newPassword);
        user.setPassword(encodedPassword);
        userRepository.updateById(user);
    }


    @Override
    public void setEnable(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }


    @Override
    public UserStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询用户】业务，参数：{}", id);
        UserStandardVO currentUser = userRepository.getStandardById(id);
        if (currentUser == null) {
            String message = "获取用户详情失败，尝试访问的用户数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return currentUser;
    }

    private void updateEnableById(Long id, Integer enable) {
        log.debug("开始处理【{}用户】的业务，ID：{}，目标状态：{}", ENABLE_TEXT[enable], id, enable);
        UserStandardVO queryResult = userRepository.getStandardById(id);
        if (queryResult == null) {
            String message = ENABLE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (queryResult.getEnable().equals(enable)) {
            String message = ENABLE_TEXT[enable] + "用户失败，当前用户已经处于"
                    + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        User user = new User();
        user.setId(id);
        user.setEnable(enable);
        log.debug("即将修改数据，参数：{}", user);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = ENABLE_TEXT[enable] + "用户失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public PageData<UserListItemVO> list(Integer pageNum) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}", pageNum);
        PageData<UserListItemVO> pageData = userRepository.list(pageNum, defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<UserListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询用户列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageData<UserListItemVO> pageData = userRepository.list(pageNum, pageSize);
        return pageData;
    }
}
